#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

source "hack/lib/test_lib.sh"

# KUBECONFIG can be an empty string and so needs to be explicitly declared to avoid an unbound variable error
KUBECONFIG=${KUBECONFIG:-""}

if [ -z "${PASSES-}" ]; then
	PASSES="fmt e2e e2eslow unit"
fi

function fmt_pass {
	if ! "./hack/k8s/codegen/verify-generated.sh"; then
		exit 1
	fi
	
	DOCKER_REPO_ROOT="/go/src/github.com/coreos/etcd-operator"
	docker run --rm \
		-v "${PWD}":"${DOCKER_REPO_ROOT}" \
		-w "${DOCKER_REPO_ROOT}" \
		gcr.io/coreos-k8s-scale-testing/etcd-operator-builder:0.4.1-2 \
		"./hack/fmt_pass"
}

function e2e_pass {
	: ${TEST_S3_BUCKET:?"Need to set TEST_S3_BUCKET"}
	: ${TEST_AWS_SECRET:?"Need to set TEST_AWS_SECRET"}

	# Run all the tests by default
	E2E_TEST_SELECTOR=${E2E_TEST_SELECTOR:-.*}

	build_flags=("-i") # cache package compilation data for faster repeated builds
	for i in {1..2}; do
		go test -failfast -parallel=4 "./test/e2e/" ${build_flags[@]} -run "$E2E_TEST_SELECTOR" -timeout 30m --race \
			--kubeconfig=$KUBECONFIG --operator-image=$OPERATOR_IMAGE --namespace=${TEST_NAMESPACE}
		build_flags=("")
	done
}

function e2eslow_pass {
	E2E_TEST_SELECTOR=${E2E_TEST_SELECTOR:-.*}
	build_flags=("-i") # cache package compilation data for faster repeated builds
	for i in {1..2}; do
		go test -failfast "./test/e2e/e2eslow" ${build_flags[@]} -run "$E2E_TEST_SELECTOR" -timeout 30m --race \
			--kubeconfig=$KUBECONFIG --operator-image=$OPERATOR_IMAGE --namespace=${TEST_NAMESPACE}
		build_flags=("")
	done
}

function upgrade_pass {
	# Run all the tests by default
	UPGRADE_TEST_SELECTOR=${UPGRADE_TEST_SELECTOR:-.*}
	go test -failfast ./test/e2e/upgradetest/ -run "$UPGRADE_TEST_SELECTOR" --race -timeout 30m \
		--kubeconfig=$KUBECONFIG --kube-ns=$TEST_NAMESPACE \
		--old-image=$UPGRADE_FROM \
		--new-image=$UPGRADE_TO
}

function unit_pass {
	DOCKER_REPO_ROOT="/go/src/github.com/coreos/etcd-operator"
	docker run --rm \
		-v "${PWD}":"${DOCKER_REPO_ROOT}" \
		-w "${DOCKER_REPO_ROOT}" \
		-e "CODECOV_TOKEN" \
		golang:1.11.5 \
		"./hack/unit_test"
}

for p in $PASSES
do
	${p}_pass
done

echo "test success ==="
